// pages/payment/bodou/index.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    packages: [],//套餐列表
    remainder: '',//剩余波豆
    isChecked: '',//vip选中样式
    vipId: '',//vip选中套餐ID
    payprice: '',//vip选中套餐价格
    openId: ''//用户的唯一标识（openid）
  },
  geturl(){
    wx.request({
      url: app.globalData.url + 'api/legal/protocol',
      data: {
        token:app.globalData.token,
      },
      method: 'POST',
      success: (e)=>{
        console.log(e)
        let url = e.data.data.url;
        this.setData({
          url: url,
        })
      },
    })
  },
  //去url页
  go_protocol(){
    wx.navigateTo({
      url: '../../protocol/protocol?url=' + this.data.url +'&title=服务协议&flag=fuwu',
    })
  },
  btn(e) {
    console.log(e)
    var index = e.currentTarget.dataset.index//点击个数
    var id = e.currentTarget.dataset.id//套餐ID
    var vippay = e.currentTarget.dataset.price; //选中价格
    this.setData({
      isChecked: index,
      vipId: id,
      payprice: vippay
    })
  },
  onGotUserInfo(e) {
    var that = this;
    if (that.data.vipId == '') {
      wx.showToast({
        title: '请选择套餐',
        icon: 'none',
      })
    } else {
      wx.showLoading({
        title: '加载中',
      })
      var timer=setTimeout(function(){
        wx.hideLoading();
        clearTimeout(timer)
      },1200)
      const encryptedData = e.detail.encryptedData;
      const iv = e.detail.iv;
      var timer = setTimeout(function () {
        wx.login({
          success(e) {
            that.setData({
              openId: e.code,
            })
            clearTimeout(timer)
            //原始支付
            // that.get_openId(that.data.openId, encryptedData, iv)
            //现支付
            if (wx.getStorageSync('openId')){
              const openId = wx.getStorageSync('openId');
              that.senpay(openId);
            }else{
              wx.showModal({
                content: '请先进行授权',
                showCancel: true,
                cancelText: '取消',
                cancelColor: '#333333',
                confirmText: '好的',
                confirmColor: '#d0a76c',
                success:(e)=>{
                  if (e.confirm){
                    wx.navigateTo({
                      url: '../../author/author',
                    })
                  }
                }
              })
            }
            
          }
        })
      }, 0)
    }
  },
  btnNav(){
    wx.navigateTo({
      url: 'bodouDetail/bodouDetail',
    })
  },
  //getRegisterInfo
  register(){
    wx.request({
      url: app.globalData.url + 'api/common/register/info',
      data: {
        token:app.globalData.token,
      },
      method: 'POST',
      success: (e)=>{
        console.log(e)
        let info = e.data.data;
        this.setData({
          info: info,
        })
      },
    })
  },
  //获取openId >> 
  get_openId(code, encryptedData, iv) {
    let that = this;
    wx.request({
      url: app.globalData.url + 'api/sign/login/getWxLogin',
      data: {
        code: code,
        encryptedData: encryptedData,
        iv: iv,
      },
      method: 'POST',
      success: function (e) {
        var aToStr = JSON.parse(e.data.data.getuserinfo); 
        let openId = aToStr.openId;
        that.senpay(openId)
      },
    })
  },
  senpay(openId) {
    var package_id = this.data.vipId;
    var pay_price = this.data.payprice;
    var that = this;
    setTimeout(function () {
      wx.hideLoading()
    }, 2000)
    wx.request({
      url: app.globalData.url + 'api/virtualCoin/create/order',
      data: {
        token: app.globalData.token,
        package_id: package_id,
        pay_price: pay_price,
        pay_method: 2,
        bought_channel: 3,
        pay_status: 0,
        openId: openId
      },
      method: 'POST',
      success: function (e) {
        console.log(e)
        if (e.data.code == 0) {
          // console.log(e)
          let _appId = e.data.data.appId,
            _nonceStr = e.data.data.nonceStr,
            _package = e.data.data.package,
            _paySign = e.data.data.paySign,
            _signType = e.data.data.signType,
            _timeStamp = e.data.data.timeStamp;
          wx.requestPayment({
            appId: _appId,
            nonceStr: _nonceStr,
            package: _package,
            paySign: _paySign,
            signType: _signType,
            timeStamp: _timeStamp,
            success(e) {
              console.log(e)
              if (e.errMsg == "requestPayment:ok") {
                wx.showModal({
                  content: '支付完成',
                  showCancel: false,
                  confirmText: '好',
                  confirmColor: '#d0a76c',
                  success: function (e) {
                    // console.log(e)
                    that.getViplist()
                    if (e.confirm) {
                    }
                  },
                })
              } else {
                wx.showModal({
                  content: '支付失败',
                  showCancel: false,
                  confirmText: '好',
                  confirmColor: '#d0a76c',
                  success: function (e) {
                    // console.log(e)
                    that.getViplist()
                    if (e.confirm) {
                    }
                  },
                })
              }

            }
          })
        }
      },
    })
  },
  getViplist() {
    var _this = this;
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    wx.request({
      url: app.globalData.url + 'api/virtualCoin/packages/list',
      data: {
        token: app.globalData.token,
        sys: 1,
      },
      method: 'POST',
      success: function (e) {
        var packages = e.data.data.packages;
        var vip_expire_time = parseInt(e.data.data.vip_expire_time);
        var packaobj = [];
        packages.forEach((res) => {
          var obj = {};
          obj.id = res.id;
          obj.coin_num = res.coin_num;
          if (res.is_sales == 1) {
            if (vip_expire_time > timestamp) {
              obj.price = res.price_sales_vip;
            } else {
              obj.price = res.price_sales;
            }
          } else {
            if (e.data.data.vip_expire_time > timestamp) {
              obj.price = res.price_vip;
            } else {
              obj.price = res.price;
            }
          }
          packaobj.push(obj);
        })
        if (e.data.code == 0) {
          _this.setData({
            packages: packaobj,
            remainder: e.data.data.virtual_coin
          })
        }
      },
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getViplist()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.geturl();
    this.register();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})